import { add as addEqpttype, getAllEqptType } from '@/api/tEqpttype';
import { dictDetailAdd } from '@/api/dictDetail';

export function submitBrand(target, fieldName) {
  const data = {
    id: '',
    label: target.form[fieldName],
    value: target.form[fieldName],
    sort: 999,
    dict: { id: 14 }
  }
  dictDetailAdd(data)
    .then(res => {
      target.$notify({
        title: '添加成功',
        type: 'success',
        duration: 2500
      })
    })
    .catch(err => {
      target.loading = false
      console.log(err)
    })
}

export function submitModelname(target, fieldName1, fieldName2) {
  // 先选择品牌，再增加
  if (target.form[fieldName1]) {
    var data = {
      name: target.form[fieldName2],
      eqptsystemid: target.form[fieldName1],
      sort: 999,
      dictDetail: { id: target.form[fieldName1] }
    }
    addEqpttype(data)
      .then(res => {
        target.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
      })
      .catch(err => {
        target.loading = false
        console.log(err)
      })
  }
}

export function getEqptModel(brand, target, fieldName) {
  target[fieldName] = []
  if (brand) {
    return getAllEqptType(brand)
  }
}

export function processEqpt(res, target, fieldName1, fieldName2) {
  target[fieldName1] = res.content
  let flag = false
  for (const index in target[fieldName1]) {
    if (target[fieldName1][index].id === target.form[fieldName2]) {
      flag = true
      break
    }
  }
  if (!flag) {
    target.form[fieldName2] = ''
  }
}

export function getEqptType(systemid, target, fieldName1, fieldName2) {
  target[fieldName1] = []
  getAllEqptType(systemid)
    .then(res => {
      target[fieldName1] = res.content
      var flag = false
      for (var index in target[fieldName1]) {
        if (target[fieldName1][index].id === target.form[fieldName2]) {
          flag = true
          break
        }
      }
      if (!flag) {
        target.form[fieldName2] = ''
      }
    })
    .catch(err => {
      console.log(err)
    })
}

export function inputValid(num, value) {
  console.log(num, value)
  var str = value
  var len1 = str.substr(0, 1)
  var len2 = str.substr(1, 1)
  // 如果第一位是0，第二位不是点，就用数字把点替换掉
  if (str.length > 1 && len1 === 0 && len2 !== '.') {
    str = str.substr(1, 1)
  }
  // 第一位不能是.
  if (len1 === '.') {
    str = ''
  }

  // 正则替换
  str = str.replace(/[^\d^\.]+/g, '') // 保留数字和小数点

  // 限制只能输入一个小数点
  if (str.indexOf('.') !== -1) {
    var str_ = str.substr(str.indexOf('.') + 1)
    if (str_.indexOf('.') !== -1) {
      str = str.substr(0, str.indexOf('.') + str_.indexOf('.') + 1)
    }
    if (str_.length > 2) {
      str = str.substr(0, str.indexOf('.') + 1) + str_.substr(0, 2)
    }
  }
  // str = str.replace(/\.\d\d\d$/,'') // 小数点后只能输两位
  return str
}
